//
//  DrawImageView.m
//  TQLSmartPen
//
//  Created by tql on 2017/10/20.
//  Copyright © 2017年 tqlZj. All rights reserved.
//

#import "DrawImageView.h"
#import "DrawGLKView.h"
#import <SmartPenSDK/SmartPenSDK.h>
#import "ToolBase.h"
#import "MyDrawView.h"
#import <YsToolsManager/YsToolsManager.h>
#import <YYKit/YYKit.h>
// 最小/大宽度


#define B5_WIDTH 119.44
#define B5_HEIGHT 168


#define A4_WIDTH 155
#define A4_HEIGHT 216


@interface DrawImageView ()<getDrawImageDelegate>
{
    
    int drawPointZ;
    float drawpointX;
    float drawpointY;
    float redoSpeed;
    BOOL firstXy;
    
    float gOffsetX;
    float gOffsetY;
    
    float gScale;
    float gpointX;
    float gpointY;
    int gWidth;
    int ipl;
    int iLimit;
    BOOL isReplay;
    int maxPageNumber;
    NSMutableString *dataStr;
   
}
@property (nonatomic, strong) DrawGLKView *MyView;
// 当前宽度
@property (nonatomic, strong) NSString *imageName;
@property (nonatomic, strong)UIColor *lineColor;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSMutableArray *dotArray;
@property (nonatomic, strong)NSMutableDictionary *allPageDictionary;

@property (nonatomic, strong)NSMutableString *xRecognizeString;
@property (nonatomic, strong)NSMutableString *yRecognizeString;
@end

@implementation DrawImageView

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        [self createDrawView];
        [self createArray];
        [self initData];
        [self updateBackgroudImageView];
    }
    return self;
}

- (void)initData {
    gOffsetX = 0;
    gOffsetY = 0;
    gScale = 1;
    _gCurPageID = -1;
    gWidth = 1;
    isReplay = NO;
    firstXy = NO;
    maxPageNumber = 0;
    self.lineColor = [UIColor blackColor];
}

- (void)createDrawView {
    
    self.userInteractionEnabled = YES;
    self.image = [UIImage imageNamed:@"ben0.png"];
    _MyView = [[DrawGLKView alloc]initWithFrame:self.bounds];
    _MyView.strokeColor = [UIColor blackColor];

    [self addSubview:_MyView];
}

- (void)getDrawImage:(UIImage *)drawImage{
    
    [self snapshotViewFromRect:self.bounds withCapInsets:UIEdgeInsetsMake(0, 0,0,0)];

}

- (void)snapshotViewFromRect:(CGRect)rect withCapInsets:(UIEdgeInsets)capInsets {
    
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(currentContext, - CGRectGetMinX(rect), - CGRectGetMinY(rect));
    [self.layer renderInContext:currentContext];
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    CGContextFlush(currentContext);
    UIGraphicsEndImageContext();
    UIImage* image = [snapshotImage resizableImageWithCapInsets:capInsets];
    self.image = image;
   
}

-(UIImage *)addImage:(UIImage *)drawImage toImage:(UIImage *)sourceImage
{
    
    
    UIGraphicsBeginImageContext(sourceImage.size);
    [sourceImage drawInRect:CGRectMake(0, 0, sourceImage.size.width,sourceImage.size.height)];
    //Draw image1
    [drawImage drawInRect:CGRectMake(0, 0, sourceImage.size.width * 3,sourceImage.size.height * 3)];
    //Draw image2
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultImage;
}

- (void)updateBackgroudImageView {
    
       maxPageNumber = 64;
      _imageName = [NSString stringWithFormat:@"page"];
    _allPageDictionary = [NSMutableDictionary dictionary];
}

- (void)dealloc {
    isReplay = NO;
    _allPageDictionary = [NSMutableDictionary dictionary];
    [_MyView removeFromSuperview];
    _MyView = nil;
    NSLog(@"%s",__FUNCTION__);
}

- (void)createArray {
    
}

- (void)clearPath {
    if (_gCurPageID < 0) {
        return;
    }
    NSMutableArray *pageArray = [self.allPageDictionary objectForKey:[NSString stringWithFormat:@"%@%d",_imageName,_gCurPageID]];
    [pageArray removeAllObjects];
    [self setBackgroundImage:_gCurPageID];
    [_MyView erase];
}
- (void)changeLineWidth:(float)width {
    
    gWidth = width;
    isReplay = NO;
}
- (void)changeLineColor :(UIColor *)color {
    _lineColor = color;
    isReplay = NO;
}

- (void)rePlay:(int)speedLevel{
    
    isReplay = YES;
    if (_gCurPageID != -1) {
        [self rePlay:_gCurPageID widthLevel:speedLevel];
    }
}

- (void)changeBookSize:(int)dataType{
    [self clearPath];
    [self initData];
    self.image = [UIImage imageNamed:@"ben0.png"];
        maxPageNumber = 64;
        _imageName = [NSString stringWithFormat:@"page"];
    
}
- (void)rePlay:(int)PageID widthLevel:(int)speedLevel{
    
    if (PageID > maxPageNumber) {
        return;
    }
    [_MyView erase];
    [self setBackgroundImage:_gCurPageID];
    ipl = 0;
    CGFloat speed = 0;
    switch (speedLevel) {
        case 1:
            speed = 0.08;
            break;
        case 2:
             speed = 0.04;
            break;
        case 3:
             speed = 0.02;
            break;
        case 4:
             speed = 0.005;
            break;
        case 5:
             speed = 0.001;
            break;
        default:
            break;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:speed target:self selector:@selector(drawStroke) userInfo:nil repeats:YES];
}

- (void)drawStroke {
    
    if (!isReplay) {
      //[_MyView erase];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self drawExistingStroke:self->_gCurPageID];
        });
        [_timer invalidate];  // 从运行循环中移除， 对运行循环的引用进行一次 release
        _timer = nil;
        return;
    }
    
    NSArray *pageDotArray = [self.allPageDictionary objectForKey:[NSString stringWithFormat:@"%@%d",_imageName,_gCurPageID]];
    
    if (pageDotArray.count == 0) {
        return;
    }
    DotStruct *dot = pageDotArray[ipl];
    _MyView.strokeColor = dot.lineColor;
        if (dot.drawType == 0) {
            [_MyView startWithScale:gScale offsetX:gOffsetX offsetY:gOffsetY penWidth:dot.penWidth x:dot.drawPointX y:dot.drawPointY force:dot.drawForce];
        } else if (dot.drawType == 1){
          [_MyView moveWithScale:gScale offsetX:gOffsetX offsetY:gOffsetY penWidth:dot.penWidth x:dot.drawPointX y:dot.drawPointY force:dot.drawForce];
        }
        else{
            [_MyView moveWithScale:gScale offsetX:gOffsetX offsetY:gOffsetY penWidth:dot.penWidth x:dot.drawPointX y:dot.drawPointY force:30];
            [_MyView end];
        }
      ipl +=1;
    if (ipl == pageDotArray.count) {
        ipl = 0;
        [_timer invalidate];  // 从运行循环中移除， 对运行循环的引用进行一次 release
        _timer=nil;
    }
}

- (void)drawExistingStroke:(int)PageID {
    
    [_MyView erase];
//    NSMutableArray *pageArr = [_allPageDictionary objectForKey:[NSString stringWithFormat:@"%@%d",_imageName,_gCurPageID]];
    NSMutableArray *pageArr = [_allPageDictionary objectForKey:[NSString stringWithFormat:@"%d",PageID]];

    if (pageArr.count  == 0) {
        return;
    }
    
    //coreGraphier重绘使用
    for (int i = 0; i < pageArr.count; i++ ) {
        
        DotStruct *dot = [pageArr objectAtIndex:i];
         _MyView.strokeColor = dot.lineColor;

        if (dot.drawType == 0) {
            
          [_MyView startWithScale:gScale offsetX:gOffsetX offsetY:gOffsetY penWidth:dot.penWidth x:dot.drawPointX y:dot.drawPointY force:dot.drawForce];
        }
        else if(dot.drawType == 1){
            
         [_MyView moveWithScale:gScale offsetX:gOffsetX offsetY:gOffsetY penWidth:dot.penWidth x:dot.drawPointX y:dot.drawPointY force:dot.drawForce];
            }
       else if(dot.drawType == 2){
          
        [_MyView moveWithScale:gScale offsetX:gOffsetX offsetY:gOffsetY penWidth:dot.penWidth x:dot.drawPointX y:dot.drawPointY force:30];
             [_MyView end];
        }
        
    }
}

- (void)drawStrokeWithArray:(NSArray <Dot *>*)dots withPageId:(NSString *)pageID
{
    NSArray *dotStructs = [dots qmui_mapWithBlock:^id(Dot *item) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        self->drawPointZ = item.force;
        NSArray *arr = [self getXandY:item];
        self->drawpointX = [arr[0] floatValue];
        self->drawpointY = [arr[1]floatValue];
        [self getDrawPoint];
        
        [dict setValue:@0 forKey:@"pageID"];
        [dict setValue:@(self->drawpointX) forKey:@"drawPointX"];
        [dict setValue:@(self->drawpointY) forKey:@"drawPointY"];
        [dict setValue:@(item.type) forKey:@"drawType"];
        [dict setValue:@(self->drawPointZ) forKey:@"drawForce"];
        [dict setValue:@1 forKey:@"penWidth"];
        [dict setValue:[UIColor colorWithHexString:@"00000080"] forKey:@"lineColor"];
        return [DotStruct modelWithJSON:dict];
    }];
    [self.allPageDictionary setValue:dotStructs forKey:pageID];
    [self drawExistingStroke:[pageID intValue]];
}


- (NSArray *)getgetcognizeArray{
    NSMutableArray *arr = [NSMutableArray array];
    NSMutableArray *pageArr = [_allPageDictionary objectForKey:[NSString stringWithFormat:@"%@%d",_imageName,_gCurPageID]];
    if (pageArr.count  == 0) {
        return nil;
    }
    for (int i = 0; i < pageArr.count; i++ ) {
        
        DotStruct *dot = [pageArr objectAtIndex:i];
        
        if (dot.drawType == 0) {
            _xRecognizeString = [NSMutableString string];
            _yRecognizeString = [NSMutableString string];
            [_xRecognizeString appendString:[NSString stringWithFormat:@"%d,",(int)dot.drawPointX]];
            [_yRecognizeString appendString:[NSString stringWithFormat:@"%d,",(int)dot.drawPointY]];
        }
        else if(dot.drawType == 1){
            [_xRecognizeString appendString:[NSString stringWithFormat:@"%d,",(int)dot.drawPointX]];
            [_yRecognizeString appendString:[NSString stringWithFormat:@"%d,",(int)dot.drawPointY]];
        }
        else if(dot.drawType == 2){
            [_xRecognizeString appendString:[NSString stringWithFormat:@"%d",(int)dot.drawPointX]];
            [_yRecognizeString appendString:[NSString stringWithFormat:@"%d",(int)dot.drawPointY]];
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:_xRecognizeString forKey:@"x"];
            [dic setObject:_yRecognizeString forKey:@"y"];
            [arr addObject:dic];
        }
    }
    return arr;
}


- (void)setBackgroundImage:(int)imageID {
  
     UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%@%d",_imageName,imageID]];
    NSData *data = UIImagePNGRepresentation(image);
    self.image = [UIImage imageWithData:data];
}

- (void)getDrawPoint {
    
            [self getPointPageWidth:B5_WIDTH pageHeight:B5_HEIGHT];
}
- (void)getPointPageWidth:(int)width pageHeight:(int)height {
   
    drawpointX *= (self.bounds.size.width);
    drawpointX /= width;
    drawpointY *= (self.bounds.size.height);
    drawpointY /= height;
    
  }
#pragma mark - Draw Method
- (void)processEachDot:(Dot *)dot offline:(BOOL)isoffline {
    if (!dot) {
        return;
    }
    isReplay = NO;
  // NSLog(@"dot.counter%d,dot.timelong%ld,dot.force%d",dot.counter,dot.timelong,dot.force);
    drawPointZ = dot.force;
    NSArray *arr = [self getXandY:dot];
    drawpointX = [arr[0] floatValue];
    drawpointY = [arr[1]floatValue];
    [self getDrawPoint];
    _MyView.strokeColor = self.lineColor;
    
    if ( drawPointZ > 0) {
        
        if (!firstXy) { //Pen Down
            firstXy = YES;
            if ( drawpointX <= 0 ||  drawpointY <= 0) {
                return;
            }
             dataStr = [NSMutableString string];
            if (dot.PageID != _gCurPageID) {
                _gCurPageID = dot.PageID;
                redoSpeed = 0;
                
               NSString *pageString = [NSString stringWithFormat:@"%@%d",_imageName,_gCurPageID];
                NSMutableArray *pageArr = [_allPageDictionary objectForKey:pageString];
                
                if (!pageArr) {
                    pageArr = [NSMutableArray array];
                    [_allPageDictionary setObject:pageArr forKey:pageString];
                }
                
                [self setBackgroundImage:dot.PageID];
                [self drawExistingStroke:_gCurPageID];
              
            }
            [_MyView startWithScale:gScale offsetX:gOffsetX offsetY:gOffsetY penWidth:gWidth x:drawpointX y:drawpointY force:dot.force];
            
            DotStruct *dotStruct =  [[DotStruct alloc]initWithDrawPointX:drawpointX drawPointY:drawpointY drawType:dot.type pangeID:_gCurPageID drawForce:drawPointZ penWidth:gWidth lineColor:self.lineColor];
           
            NSMutableArray *pageArr = [_allPageDictionary objectForKey:[NSString stringWithFormat:@"%@%d",_imageName,_gCurPageID]];
            [pageArr addObject:dotStruct];
        }
        else{ //Pen Move
            if ( drawpointX <= 0 ||  drawpointY <= 0) {
                return;
            }//防止无效码影响
            [_MyView moveWithScale:gScale offsetX:gOffsetX offsetY:gOffsetY penWidth:gWidth x:drawpointX y:drawpointY force:dot.force];
            if (_gCurPageID >  maxPageNumber || _gCurPageID < 0) {
                return;
            }
           
            DotStruct *dotStruct =  [[DotStruct alloc]initWithDrawPointX:drawpointX drawPointY:drawpointY drawType:dot.type pangeID:_gCurPageID drawForce:drawPointZ penWidth:gWidth lineColor:self.lineColor];
            NSMutableArray *pageArr = [_allPageDictionary objectForKey:[NSString stringWithFormat:@"%@%d",_imageName,_gCurPageID]];
            [pageArr addObject:dotStruct];
        }
    }
    
    else { // pen up
        
        if (dot.type == PEN_UP) {
            if ( drawpointX <= 0 ||  drawpointY <= 0) {
                return;
            }//防止无效码影响
            firstXy = NO;
            DotStruct *dotStruct =  [[DotStruct alloc]initWithDrawPointX:drawpointX drawPointY:drawpointY drawType:dot.type pangeID:_gCurPageID drawForce:drawPointZ penWidth:gWidth lineColor:self.lineColor];
            NSMutableArray *pageArr = [_allPageDictionary objectForKey:[NSString stringWithFormat:@"%@%d",_imageName,_gCurPageID]];
            [pageArr addObject:dotStruct];
             [_MyView moveWithScale:gScale offsetX:gOffsetX offsetY:gOffsetY penWidth:gWidth x:drawpointX y:drawpointY force:30];
            [_MyView end];
            drawpointX = 0;
            drawpointY = 0;
        
        }
    }
}

- (NSArray *)getXandY:(Dot *)dot {
    
    float tmpx1 = dot.x;
    //x
    float pointX1 = dot.fx;
    pointX1 /= 100.0;
    pointX1 += tmpx1;
    float tmpy1 = dot.y;
    //y
    float pointY1 = dot.fy;
    pointY1 /= 100.0;
    pointY1 += tmpy1;
    return @[@(pointX1),@(pointY1)];
    
}

@end
